/**
* @author Roger Wu
*/

(function ($) {
    var allSelectBox = [];
    var killAllBox = function (bid) {
        $.each(allSelectBox, function (i) {
            if (allSelectBox[i] != bid) {
                if (!$("#" + allSelectBox[i])[0]) {
                    $("#op_" + allSelectBox[i]).remove();
                    //allSelectBox.splice(i,1);
                } else {
                    $("#op_" + allSelectBox[i]).css({ height: "", width: "" }).hide();
                }
                $(document).unbind("click", killAllBox);
            }
        });
    };

    $.extend($.fn, {
        comboxSelect: function (options) {
            var op = $.extend({ selector: ">a" }, options);

            return this.each(function () {
                var box = $(this);
                var selector = $(op.selector, box);

                allSelectBox.push(box.attr("id"));
                $(op.selector, box).click(function () {
                    var options = $("#op_" + box.attr("id"));
                    if (options.is(":hidden")) {
                        if (options.height() > 300) {
                            options.css({ height: "300px", overflow: "scroll" });
                        }
                        var top = box.offset().top + box[0].offsetHeight - 50;
                        if (top + options.height() > $(window).height() - 20) {
                            top = $(window).height() - 20 - options.height();
                        }
                        options.css({ top: top, left: box.offset().left }).show();
                        killAllBox(box.attr("id"));
                        $(document).click(killAllBox);
                    } else {
                        $(document).unbind("click", killAllBox);
                        killAllBox();
                    }
                    return false;
                });
                $("#op_" + box.attr("id")).find(">li").comboxOption(selector, box);
            });
        },
        comboxOption: function (selector, box) {
            return this.each(function () {
                $(">a", this).click(function () {
                    var $this = $(this);
                    $this.parent().parent().find(".selected").removeClass("selected");
                    $this.addClass("selected");
                    selector.text($this.text());

                    var $input = $("select", box);
                    if ($input.val() != $this.attr("value")) {
                        $("select", box).val($this.attr("value")).trigger("change");
                    }
                });
            });
        },
        combox: function () {

            /* 清理下拉层 */
            var _selectBox = [];
            $.each(allSelectBox, function (i) {
                if ($("#" + allSelectBox[i])[0]) {
                    _selectBox.push(allSelectBox[i]);
                } else {
                    $("#op_" + allSelectBox[i]).remove();
                }
            });
            allSelectBox = _selectBox;

            return this.each(function (i) {
                var $this = $(this).removeClass("combox");

                function getValue($obj) {
                    var value = '';
                    if (typeof ($obj.attr('selected_value')) != 'undefined') {
                        value = $obj.attr('selected_value');
                    }
                    else {
                        value = $obj.attr('value');
                    }
                    return value;
                }

                function setHtml($obj) {
                    var value = $obj.attr('value');
                    var label = $obj.find("option[value=" + value + "]", navTab.getCurrentPanel()).text();
                    var name = $obj.attr("name");

                    //var ref = $obj.attr("ref");
                    //var category = $obj.attr("category");
                    //var data_url = $obj.attr("data_url") || "";
                    //var cid = $obj.attr("id") || Math.round(Math.random() * 10000000);
                    var cid = Math.round(Math.random() * 10000000);

                    //var select = '<div class="combox"><div id="combox_' + cid + '" class="select"' + (ref ? ' ref="' + ref + '"' : '') + '>';
                    var select = '<div class="combox"><div id="combox_' + cid + '" class="select">';
                    select += '<a href="javascript:" class="' + $this.attr("class") + '" name="' + name + '" value="' + value + '">' + label + '</a></div></div>';
                    var options = '<ul class="comboxop" id="op_combox_' + cid + '">';

                    $("option", $obj).each(function () {
                        var option = $(this);
                        options += "<li><a class=\"" + (value == option[0].value ? "selected" : "") + "\" href=\"#\" value=\"" + option[0].value + "\">" + option[0].text + "</a></li>";
                    });
                    options += "</ul>";

                    $("body").append(options);
                    //alert(select);
                    $obj.after(select);
                    $("div.select", $obj.next()).comboxSelect().append($obj);

                    $obj.trigger("change");
                }


                var category = $this.attr("category");
                var data_url = $this.attr("data_url") || "";

                if (data_url != '') {
                    loadData($this, function () {
                        setHtml($this);
                    })
                } else if ($this.attr("ref")) {
                } else {
                    setHtml($this);
                }
                //根节点
                //if ($this.attr("data_url") && $("select[ref=" + $this.attr("category") + "]", navTab.getCurrentPanel()).size() == 0) {
                //    loadData($this.attr("category"), function () {
                //        setHtml($this);
                //    });
                //} else if ($this.attr("ref")) {
                //} else {
                //    setHtml($this);
                //}


                if ($this.attr("ref")) {
                    function _onchange(event) {
                        var groupfilter = '';
                        var group = $this.attr("group") || "";
                        if (group != '') {
                            groupfilter = '[group=' + group + ']';
                        }
                        var $refObj = $("select[category=" + $this.attr("ref") + "]" + groupfilter, navTab.getCurrentPanel());
                        loadData($refObj, function () {
                            setHtml($refObj);
                        });
                    }
                    $this.unbind("change", _onchange).bind("change", _onchange);
                }

                function loadData($obj, handler) {

                    //var $ref = $("select[category=" + ref + "]", navTab.getCurrentPanel());
                    //alert(ref + $ref.attr('tag'));
                    var data_url = $obj.attr("data_url") || "";

                    var value = getValue($obj);
                    //获取当前combo祖先的vals
                    var vals = '';
                    var cate = $obj.attr("category") || "";
                    if (cate != '') {
                        var groupfilter = '';
                        var group = $this.attr("group") || "";
                        if (group != '') {
                            groupfilter = '[group=' + group + ']';
                        }
                        var $prt = $("select[ref=" + cate + "]" + groupfilter, navTab.getCurrentPanel());
                        if ($prt.size() > 0 && ($prt.attr('value') == '' || $prt.attr('value') == $prt.attr('empty_key'))) {

                            var defval = ($obj.attr('empty_key') ? $obj.attr('empty_key') : '-1');
                            var html = '<option value="' + defval + '">' + ($obj.attr('empty_text') ? $obj.attr('empty_text') : '--请选择--') + '</option>';
                     

                            var $refCombox = $obj.parents("div.combox:first");
                            $obj.html(html).insertAfter($refCombox);
                            $refCombox.remove();
                            if (handler) {
                                handler();
                            } else {
                                $obj.trigger("change").combox();
                            }
                            return;
                        }
                        else while ($prt.size() > 0) {
                            vals += $prt.attr('category') + ':' + $prt.attr('value') + ";";
                            $prt = $("select[ref=" + $prt.attr('category') + "]", navTab.getCurrentPanel());
                        }
                    }
                    $.ajax({
                        type: 'POST', dataType: "text", url: data_url.replace("{value}", vals), cache: false,
                        data: {},
                        success: function (data) {
                            var json = $.parseJSON(data);

                            if (json.ErrorCode != '0000') {
                                alertMsg.error(json.ErrorMsg);
                                //handler();
                            } else {
                                var defval = ($obj.attr('empty_key') ? $obj.attr('empty_key') : '-1');
                                var html = '<option value="' + defval + '">' + ($obj.attr('empty_text') ? $obj.attr('empty_text') : '--请选择--') + '</option>';
                                $(json.Result.List).each(function () {
                                    html += '<option value="' + this.Key + '" ' + (this.Key == value ? 'selected' : '') + '>' + this.Value + '</option>';
                                });
                                var $refCombox = $obj.parents("div.combox:first");
                                $obj.html(html).insertAfter($refCombox);
                                $refCombox.remove();
                                if (handler) {
                                    handler(json.Result);
                                } else {
                                    $obj.trigger("change").combox();
                                }
                            }
                        },
                        error: DWZ.ajaxError
                    });
                }

            });
        }
    });
})(jQuery);
